import {defineStore} from 'pinia'
import defaultAvatar from '@/assets/SzauKZv.png'
import {Role, User} from "@utils/resource";
import util from "@utils/util";
import {menuStore} from "@/store/menu";
import {commonStore} from "@/store/common";

const commonS = commonStore()
export const appStore = defineStore({
    id: 'app',
    state: () => ({
        user: {
            avatar: defaultAvatar,
            id: -1,
            name: "",
            nick: "",
            roleId: -1,
        },
        currentRole: {
            name: "",
            id: -1
        },
        roles: []
    }),
    persist: true,
    getters: {
        getUserName: (state) => state.user.name,
        getNick: (state) => {
            return util.isNull(state.user.nick) ? state.user.name : state.user.nick
        },
    },
    actions: {
        login(params, sucCallback, errCallback) {
            User.login(params).then(res => {
                if (res.code === 0) {
                    let user1 = res.data
                    user1.pass = ''
                    // store.$patch({user:user1})
                    this.user = user1
                    if (this.user.avatar == null) {
                        this.user.avatar = defaultAvatar
                    }
                    Role.userRole(this.user.name).then(res => {
                        this.currentRole = res.data[0]
                        sucCallback(res)
                    })
                } else {
                    errCallback(res)
                }
            }).catch(err=>{errCallback(null,err)})

        },
        getCurrentRole() {
            return this.currentRole
        },
        getUser() {
            return this.user
        },
        loadRoles() {
            Role.userRole(this.user.name).then(res => {
                this.currentRole = res.data[0]
                this.roles = res.data

            }).catch(e => console.error(e))
        },
        updateCurrentRole(role) {
            commonS.loading = true
            Role.setCurrentRole(role).then(res => {
                if (res.data.code === 0) {
                    this.currentRole = res.data.data
                    menuStore.updateMenus()
                }
                commonS.loading = false
            }).catch(e => console.error(e))

        }
    }
})

